How do I use the GROUP BY clause to aggregate data in SQL Server?
How do I use the GROUP BY clause to aggregate data in SQL Server?
147
11-Jul-2024
Updated on 12-Jul-2024
Ravi Vishwakarma
12-Jul-2024The
GROUP BY
clause in SQL Server is used to group rows that have the same values in specified columns into aggregate data, such as sums, averages, counts, etc. Here is a step-by-step guide on how to use theGROUP BY
clause:Basic Syntax
Aggregate Functions
Common aggregate functions include:
SUM()
COUNT()
AVG()
MIN()
MAX()
Example Use Cases
1. Sum of Sales by Salesperson
Assume we have a table
Sales
with the following columns:SaleID
,SaleAmount
,SalesPersonID
, andSaleDate
.To calculate the total sales amount for each salesperson:
Output:
2. Count of Sales by Salesperson
To count the number of sales made by each salesperson:
Output:
3. Average Sale Amount by Salesperson
To calculate the average sale amount for each salesperson:
Output:
Using GROUP BY with Multiple Columns
You can group by multiple columns to get more granular aggregates.
Output:
Filtering Groups with HAVING
The
HAVING
clause is used to filter groups based on aggregate functions.Example: Total Sales Greater than 300
Output:
Complete Example
Combining everything together, here is a full example including table creation, data insertion, and querying with
GROUP BY
andHAVING
:Read more
Write a query to retrieve the total number of employees in each department.
How do I use CTE to simplify complex queries in SQL Server?
Difference between INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN in SQL Server.